package com.demo.reentrantLock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class LockOverTime {
    private static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(() -> {
            log.debug("尝试获取锁");
            try {
                if (!lock.tryLock(2, TimeUnit.SECONDS)) {
                    log.debug("没有获取到锁");
                    return;
                }
            } catch (InterruptedException e) {
                log.debug("没有获取到锁");
                e.printStackTrace();
                return;
            }

            try {
                log.debug("获取到锁");
            } catch (Exception e) {
                lock.unlock();
            }
        }, "t1");
        //主线程先获取锁
        lock.lock();
        log.debug("主线程获取锁");
        t1.start();
        Thread.sleep(1000);
        lock.unlock();
        log.debug("主线程释放锁");
    }
}
